package com.amigo.online.provider.ffmpeg.config;

import com.amigo.online.provider.ffmpeg.entity.UserTbl;
import com.amigo.online.provider.ffmpeg.entity.VideoTbl;
import com.amigo.online.provider.ffmpeg.entity.VideoTblExample;
import com.amigo.online.provider.ffmpeg.mapper.UserTblMapper;
import com.amigo.online.provider.ffmpeg.mapper.VideoTblMapper;
import com.amigo.online.provider.ffmpeg.rocketmq.consumer.VideoAddWatermarkConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自动给视频加水印
 * @author pangdonghao
 * @version 1.0
 * @csdn https://blog.csdn.net/pangdongh
 * @createDate 2019/10/12 11:30
 */
@Component
@Slf4j
public class AutoHandleVideo implements ApplicationRunner {
    @Autowired
    VideoAddWatermarkConsumer videoAddWatermarkConsumer;
    @Autowired
    VideoTblMapper videoTblMapper;
    @Autowired
    UserTblMapper userTblMapper;

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

    volatile AtomicInteger count= new AtomicInteger(0);
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //创建定时器
        Timer timer = new Timer();
        //每2秒执行一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(12313);
                if(count.intValue() <=0){
                    start();
                }
            }
        }, 0,2000);
    }
    private void start(){
        VideoTblExample videoTblExample = new VideoTblExample();
        videoTblExample.createCriteria().andWatermarkVideoIsNull();
        List<VideoTbl> videoTblList = videoTblMapper.selectByExample(videoTblExample);
        for (VideoTbl videoTbl : videoTblList){
            System.out.println(videoTbl);
            if(videoTbl.getId()!=null){
                UserTbl userTbl = userTblMapper.selectByPrimaryKey(videoTbl.getUserId());
                if (userTbl!=null){
                    fixedThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            try{
                                count.getAndIncrement();
                                videoAddWatermarkConsumer.handleVideo(videoTbl, userTbl);
                            }finally {
                                count.decrementAndGet();
                            }
                        }
                    });
                }
            }
        }
    }
}
